import { http } from "@/utils/http";

export interface RoleItem {
  id?: number;
  name: string;
  pname?: string;
  description?: string;
  createTime?: string;
}

export interface RoleListResult {
  code: number;
  data: {
    total: number;
    list: RoleItem[];
    pageNum: number;
    pageSize: number;
    size: number;
    startRow: number;
    endRow: number;
    pages: number;
    prePage: number;
    nextPage: number;
    isFirstPage: boolean;
    isLastPage: boolean;
    hasPreviousPage: boolean;
    hasNextPage: boolean;
    navigatePages: number;
    navigatepageNums: number[];
    navigateFirstPage: number;
    navigateLastPage: number;
  };
  message: string;
}

export interface RoleDetailResult {
  code: number;
  data: RoleItem;
  message: string;
}

export interface RoleCreateResult {
  code: number;
  data: number; // 返回新创建的角色ID
  message: string;
}

export interface RoleUpdateResult {
  code: number;
  data: boolean;
  message: string;
}

export interface RoleDeleteResult {
  code: number;
  data: boolean;
  message: string;
}

export interface UpdateRolePermissionParams {
  roleId: number;
  permissionIds: number[];
}

export interface UpdateRolePermissionResult {
  code: number;
  data: boolean;
  message: string;
}

/** 获取角色列表 */
export const getRoleList = (data?: {
  page?: number;
  limit?: number;
  name?: string;
}) => {
  return http.request<RoleListResult>("post", "role/list", { data });
};

/** 获取角色详情 */
export const getRoleDetail = (id: number) => {
  return http.request<RoleDetailResult>("get", "role", { params: { id } });
};

/** 创建角色 */
export const createRole = (data: Omit<RoleItem, "id" | "createTime">) => {
  return http.request<RoleCreateResult>("post", "role/add", { data });
};

/** 更新角色 */
export const updateRole = (id: number, data: Partial<RoleItem>) => {
  return http.request<RoleUpdateResult>("post", "role/update", {
    data: { id, ...data }
  });
};

/** 删除角色 */
export const deleteRole = (id: number) => {
  return http.request<RoleDeleteResult>("get", "role/delete", {
    params: { id }
  });
};

/** 批量删除角色 */
export const batchDeleteRole = (ids: number[]) => {
  return http.request<RoleDeleteResult>("post", "role/batchDelete", {
    data: { ids }
  });
};

// ========== 权限相关（用于默认勾选） ==========
export interface RolePermissionNamesResult {
  code: number;
  data: string[]; // 如：["系统管理,用户管理,角色管理,菜单管理"]
  message: string;
}

/** 根据（角色）用户ID查询已拥有的权限名称（逗号分隔的字符串数组） */
export const findPermissionByUserId = (id: number) => {
  // 约定以查询参数形式传递 id
  return http.request<RolePermissionNamesResult>(
    "get",
    `role/findPermissionByUserId?id=${id}`
  );
};

/** 新增/更新角色权限 */
export const updateRolePermission = (data: UpdateRolePermissionParams) => {
  return http.request<UpdateRolePermissionResult>(
    "post",
    "role/updateRolePermission",
    { data }
  );
};
